<?php
require_once('Validator.class.php');
require_once('CRM.class.php');

class MyAccount
{
	 public $user_data;
	
	 public function __construct($user_id="def")
	 {
		 if ($user_id=="def")
		 {
			 $user_id=$_SESSION['user_id'];
		 }		 
		 
		 $data=SQL::select(Template::render("getUserData.sql", "sql", array('id'=>$user_id)));		 
		 		 
		 if($data)
		 {
			 if ($data[0]['id']==$_SESSION['user_id'])
			 {
				 $this->user_data['my_user']=true;
				 $this->user_data['is_friend']=false;
			 }
			 else
			 {
				 $this->user_data['my_user']=false;
				 $this->user_data['is_friend']=self::isFriend($user_id);
			 }
			 $this->user_data['exist']=true;
			 $this->user_data['id']=$data[0]['id'];
			 $this->user_data['firstName']=$data[0]['first_name'];
			 $this->user_data['lastName']=$data[0]['last_name'];
			 $this->user_data['dateOfBirth']=$data[0]['date_of_birth'];
			 $this->user_data['dateOfBirthDate']=$data[0]['date_of_birth'];
			 $this->user_data['squat']=$data[0]['squat'];
			 $this->user_data['benchpress']=$data[0]['benchpress'];
			 $this->user_data['deadlift']=$data[0]['deadlift'];
			 $this->user_data['height']=$data[0]['height'];
			 $this->user_data['weight']=$data[0]['weight'];
			 $this->user_data['federation']=$data[0]['federation'];
			 $this->user_data['federationArray']=$data[0]['federation'];
			 $this->user_data['level']=$data[0]['first_name'];
			 $this->user_data['avatar']=$data[0]['avatar'];
			 $this->user_data['region']=$data[0]['region'];
			 $this->user_data['city']=$data[0]['city'];
			 $this->user_data['country']=$data[0]['country'];
			 $this->user_data['level']=$data[0]['level'];			 
			 $this->user_data['name']= $this->user_data['firstName'].' '. $this->user_data['lastName'];
			 $this->splitLocation();
			 $this->user_data['age']=$this->getAgeFromDate($this->user_data['dateOfBirth']);
			 
			 if (!empty($this->user_data['level']))
			 {
				 $this->convertLevel($this->user_data['level']);
			 }
			 if (!empty($this->user_data['federation']))
			 {
				 $this->convertFederation($this->user_data['federation']);
			 }
			  if (!empty($this->user_data['dateOfBirth']))
			 {
				 $this->convertDateOfBirth($this->user_data['dateOfBirth']);
			 }			 
			  if (!empty($this->user_data['squat']))
			 {
				 $this->user_data['squat']=$this->deleteDotNullResult($this->user_data['squat']);				
			 }
			  if (!empty($this->user_data['benchpress']))
			 {
				 $this->user_data['benchpress']=$this->deleteDotNullResult($this->user_data['benchpress']);	
			 }
			  if (!empty($this->user_data['deadlift']))
			 {
				 $this->user_data['deadlift']=$this->deleteDotNullResult($this->user_data['deadlift']);	
			 }
			 			 
		 }
		 else
		 {
			 $this->user_data['exist']=false;
		 }
	 }
	 
	 private function convertLevel($level, $lang="ru")
	 {
		 $levelArray=array
		 (
			 "ru"=>array
				 (
					 "zms"=>"ЗМС",
					 "msmc"=>"МСМК",
					 "ms"=>"МС",
					 "kms"=>"КМС",
					 "1man"=>"1-й взрослый",
					 "2man"=>"2-й взрослый",
					 "3man"=>"3-й взрослый",
					 "1jun"=>"1-й юношеский",
					 "2jun"=>"2-й юношеский",
					 "3jun"=>"3-й юношеский"
				 )
		 );
		 		 
		 switch ($lang)
		 {
			 case "ru":				 
			     $this->user_data['level']=$levelArray['ru'][$this->user_data['level']]; 
				 break;
			 
		 }
	 }
	 
	 private function convertDateOfBirth($dateOfBirth, $lang="ru")
	 {
		 $monthArray=array
		 (
			"ru"=>array
			(
				 "January"=>"Января",
				 "February"=>"Февраля",
				 "March"=>"Марта",
				 "April"=>"Апреля",
				 "May"=>"Мая",
				 "June"=>"Июня",
				 "July"=>"Июля",
				 "August"=>"Августа",
				 "September"=>"Сентября",
				 "October"=>"Октября",
				 "November"=>"Ноября",
				 "December"=>"Декабря"
			 )
		 );
		  switch ($lang)
		 {
			 case "ru":
				 setLocale(LC_ALL, 'ru_RU.CP1251');
				 $this->user_data['dateOfBirth']=strftime('%d %B %Y', strtotime($dateOfBirth)); 
				 $this->user_data['dateOfBirth']=str_replace(strftime('%B', strtotime($dateOfBirth)), $monthArray['ru'][strftime('%B', strtotime($dateOfBirth))], $this->user_data['dateOfBirth']);
				 break;
			 
		 }	 
	 }
	 
		 
	  private function deleteDotNullResult($result)
	 {
		 if (strpos($result,".0")!==false)
		 {
			 return str_replace(".0", "", $result);
		 }
		 else 
		 {
			 return $result;
		 } 
	 }
	 
	 private function convertFederation($federation)
	 {
		 $federationArray=array
		 (
			 "ipf"=>"IPF",
			 "wpc"=>"WPC",
			 "wpo"=>"WPO",
			 "gpc"=>"GPC",
			 "wdfpf"=>"WDFPF",
			 "awpc"=>"AWPC",
			 "ipa"=>"IPA",
			 "gpu"=>"GPU",
			 "udfpf"=>"UDFPF",
			 "raw"=>"RAW"
		 );
		 
		 $federation=unserialize($federation);
		 $this->user_data['federation']='';
		 foreach ($federation as $k=>$v)
		 {
			 if ($v)
			 {
				$this->user_data['federation']=$this->user_data['federation'].$federationArray[$k].", ";
			 }
		 }
		 $this->user_data['federation']= substr_replace($this->user_data['federation'], "", -2, -1);	
	 }
	 
	 private function splitLocation()
	 {
		 if (!empty($this->user_data['country']))
		 {
			 $this->user_data['location'] = $this->user_data['country'];
		 }
		 if (!empty($this->user_data['region']))
		 {
			 if (!empty($this->user_data['location']))
			 {
				 $this->user_data['location']= $this->user_data['location'].', '. $this->user_data['region'];
			 }
			 else
			 {
				  $this->user_data['location']=$this->user_data['region'];
			 }
		 }
		 if (!empty($this->user_data['city']))
		 {
			 if (!empty($this->user_data['location']))
			 {
				 $this->user_data['location']= $this->user_data['location'].', '. $this->user_data['city'];
			 }
			 else
			 {
				  $this->user_data['location']= $this->user_data['city'];
			 }
		 }
	 }
	 
	 public function getUserData()
	 {
		 return $this->user_data;
	 }
	 
	 private function getAgeFromDate($date)
	 {
        return floor((time()-strtotime($date))/(60*60*24*365.25));
	 }
	 
	 public static function saveUserData($userDataArray)
	 {
		 $validUserDataArray=Validator::validUserData($userDataArray);
				 
		 if (!$validUserDataArray['validated'])
		 {
			 die ('ERROR: ' . 'Not validated User Data before saving: '. $validUserDataArray['valid_message']);
		 }
		 $queryData=array
		 (
			 'first_name'=> $validUserDataArray['firstName'],
			 'last_name'=> $validUserDataArray['lastName'],
			 'date_of_birth'=> $validUserDataArray['date_of_birth'],
			 'squat'=> $validUserDataArray['squat'],
			 'benchpress'=> $validUserDataArray['press'],
			 'deadlift'=> $validUserDataArray['deadlift'],
			 'height'=> $validUserDataArray['height'],
			 'weight'=> $validUserDataArray['weigth'],
			 'federation'=> $validUserDataArray['federation'],
			 'level'=> $validUserDataArray['level'],
			 'region_id'=> $validUserDataArray['region'],
			 'city_id'=> $validUserDataArray['city'],
			 'country_id'=> $validUserDataArray['contry'],
			 'id'=> $_SESSION['user_id']
		 );
		 
		 return SQL::execute(Template::render("saveUserData.sql", "sql", $queryData));	 
	 }
        
     public static function getUserAlbums($table, $p_id="my_id")
     {
         if ($p_id=="my_id")
		 {
			 $p_id=$_SESSION['user_id'];
		 }
		 $data=SQL::select(Template::render("getUserPhotoAlbums.sql", "sql", array('id'=>$p_id, 'table'=>$table)));
         if ($data)
         {
             return ($data);
         }
         else 
         {
             return false;
         }
     }
	
     public static function createAlbum($name, $table='photoalbums')
	 {
		 SQL::execute(Template::render("createPhotoAlbum.sql", "sql", array('pu_users_id'=>$_SESSION['user_id'],'title'=>$name, 'table'=>$table)));
	 }     
     	 
	 public static function deleteAlbum($id, $table='photoalbums')
	 {
		 SQL::execute(Template::render("deletePhotoAlbum.sql", "sql", array('id'=>$id, 'table'=>$table)));
	 }
     	 
	 public static function editAlbum($id, $name, $table='photoalbums')
	 {
		 SQL::execute(Template::render("editPhotoAlbum.sql", "sql", array('id'=>$id, 'title'=>$name, 'table'=>$table)));
	 }
     
     public static function getPhotosFromAlbum($photoalbum_id, $p_id="my_id")
	 {
		 if ($p_id=="my_id")
		 {
			 $p_id=$_SESSION['user_id'];
		 }
		 
		 $data=SQL::select(Template::render("getPhotosFromAlbum.sql", "sql", array('pu_users_id'=>$p_id, 'photoalbum_id'=>$photoalbum_id)));
         if ($data)
         {
             return ($data);
         }
         else 
         {
             return false;
         }
	 }
     
     public static function getVideosFromAlbum($videoalbum_id, $p_id="my_id")
	 {
		 if ($p_id=="my_id")
		 {
			 $p_id=$_SESSION['user_id'];
		 }
		 
		 $data=SQL::select(Template::render("getVideosFromAlbum.sql", "sql", array('pu_users_id'=>$p_id, 'videoalbum_id'=>$videoalbum_id)));
         if ($data)
         {
             return ($data);
         }
         else 
         {
             return false;
         }
	 }
     
     public static function updatePhotoOrVideoName($link_name, $user_id, $table_name, $title)
	 {
		 SQL::execute(Template::render("updatePhotoOrVideoName.sql", "sql", array('user_id'=>$user_id, 'title'=>$title, 'table'=>$table_name, 'link_name'=>$link_name)));
	 }
     
      public static function deletePhotoOrVideo($link_name, $user_id, $table_name)
	 {
		 SQL::execute(Template::render("deletePhotoOrVideo.sql", "sql", array('user_id'=>$user_id, 'table'=>$table_name, 'link_name'=>$link_name)));
         
         if ($table_name=='photos')
         {
             if (file_exists('../user_photos/full_size/'.$link_name)) 
             {  
                 unlink('../user_photos/full_size/'.$link_name);
             }
             if (file_exists('../user_photos/mini/'.$link_name)) 
             {  
                 unlink('../user_photos/mini/'.$link_name);
             }             
         }
	 }
     
      public static function uploadVideo($link_name, $user_id, $videoalbum_id, $time)
     {
         if (!Validator::validUrl($link_name))
         {
             return false;
         }
         else
         {
             $link_key=substr($link_name,strpos($link_name,'watch?v')+8);
             SQL::execute(Template::render("uploadVideo.sql", "sql", array('link_key'=>$link_key, 'user_id'=>$user_id, 'title'=>"Без названия", 'pu_videoalbums_id'=>$videoalbum_id, 'date'=>$time)));  
             return $link_key;
         }
             
     }
	 
	 public static function isFriend($p_friend_id)
	 {
		  return (boolean) SQL::num_rows(Template::render("isFriend.sql", "sql", array('user_id'=>$_SESSION['user_id'],'friend_id'=>$p_friend_id)));
	 }
	 
	  public static function addToFriends($p_friend_id)
	 {
		  return SQL::execute(Template::render("addToFrinds.sql", "sql", array('user_id'=>$_SESSION['user_id'],'friend_id'=>$p_friend_id)));
	 }
	 
	 public static function deleteFromFriends($p_friend_id)
	 {
		  return SQL::execute(Template::render("deleteFromFrinds.sql", "sql", array('user_id'=>$_SESSION['user_id'],'friend_id'=>$p_friend_id)));
	 }
	 
	 public static function getMyFriends()
	 {
		  $data=SQL::select(Template::render("getMyFriends.sql", "sql", array('my_id'=>$_SESSION['user_id'])));
		  if ($data)
         {
             return ($data);
         }
         else 
         {
             return false;
         }
	 }
	 
	 public static function isEmailRegister($p_email)
	 {
		 if (!Validator::valid_email($p_email))
         {
             return false;
         }
		 
		 return (boolean)SQL::num_rows(Template::render("isEmailRegister.sql", "sql", array('email'=>$p_email)));
	 }
	 
	 public static function sendPasswordLink($p_email)
	 {
		 $data=SQL::select(Template::render("isEmailRegister.sql", "sql", array('email'=>$p_email)));
		 $user_id=$data[0]['id'];
		 
		 $first_part=mt_rand(1000, 9999);
		 $second_part=mt_rand(1000, 9999);
		 $third_part=mt_rand(1000, 9999);
		 $total_int=md5($first_part.$second_part.$third_part);	
		 
		 SQL::execute(Template::render("insertRecoveryCode.sql", "sql", array
		 (
			 'code'=>$total_int,			
			 'users_id'=>$user_id
		 )));
		
		 CRM::RecoveryLink($p_email, $total_int);
	 }
	 
	 public static function getRecoveryCode($p_code)
	 {
		 $data=SQL::select(Template::render("getRecoveryCode.sql", "sql", array('code'=>$p_code)));
		 
		 if ($data)
		{
			 return $data;
		}
		else
		{
			 return false;
		}
		
	 }
	 
	 public static function updatePassword($p_user_id, $p_password)
	 {
		 $new_pass=md5($p_password);
		 $data=SQL::execute(Template::render("updatePassword.sql", "sql", array('password'=> $new_pass, 'user_id'=>$p_user_id)));
		 CRM::NewPassword($_SESSION['email'], $new_pass);
		 return $new_pass;
	 }	
	 
	  public static function updateRecoveryTable($p_code)
	 {
		 $data=SQL::execute(Template::render("updateRecoveryTable.sql", "sql", array('code'=>$p_code)));
	 }	
	 
}